package com.xpresso.utils.email.queue;

import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.dataAccess.*;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.xpresso.utils.email.*;
import com.xpresso.utils.exceptions.XpressoException;
import com.xpresso.utils.strings.ArrayWorker;

public class SimpleEmailQueueManager implements EmailQueueManager {

	protected final String INSERT_EMAIL_QUEUE = "INSERT INTO emq_email_queue (FromName," +
			" ToName, FromEmail, ToEmail, Subject, Body, Sent, Comments, CreationDate) values(?,?,?,?,?,?,?,?, NOW())";
	protected final String UPDATE_EMAIL_QUEUE = "UPDATE emq_email_queue SET Sent='Y', " +
			"SentDate = NOW(), Comments=? WHERE IdEmailQueue = ?";
	private static final Logger log = Logger.getLogger(SimpleEmailQueueManager.class);
	
	protected QueueConfiguration config;
	
	public void setup(QueueConfiguration config) {
		this.config = config;
	}
	
	public void addEmailToQueue(EmailMessage email) throws XpressoException {
		ApplicationDataSource ads = config.getApplicationDataSource();
		Query q = new Query();
		q.setQuery(INSERT_EMAIL_QUEUE);
		q.setValues(new String[]{
				email.getFromName(),
				ArrayWorker.getStringFromArray(email.getToName(), ";"),
				email.getFrom(),
				ArrayWorker.getStringFromArray(email.getTo(), ";"),
				email.getSubject(),
				email.getBody(),
				"N",
				""
		});
		try {
			ads.executeQuery(q);
		} catch (DataSourceException e) {
			throw new XpressoException("There was a problem adding email to queue.", e);
		}
		log.info("An email with subject: " + email.getSubject() + 
				" to: "+ email.getTo()[0] + ". Has been added to the queue.");
	}

	public void runQueue(QueueCommand command) throws XpressoException {
		log.info("The email queue was called. Command: " + command.getCommand());
		ApplicationDataSource ads = config.getApplicationDataSource();
		Query q = new Query();
		q.setQuery(command.getCommand());
		q.setValues((String[])command.getParameters());
		GenericResultSet grs = null;
		try {
			grs = ads.runQuery(q);
		} catch (DataSourceException e) {
			log.error("There was executing command to get queue: " + e.getMessage()+ "; " + e.getStackTrace());
			throw new XpressoException("There was a problem getting the queue.", e);
		}
		log.info("The command was executed succesfully. " + grs.getNumberOfRows() + " emails to send.");		
		while(grs.nextRow()){
			EmailMessage email = getEmailFromGrs(grs);
			SimpleEmailProvider sep = new SimpleEmailProvider();
			sep.configure(command.getEmailConfiguration());
			String comments = "Email sent succesfully";
			try {
				sep.sendEmail(email);
			} catch (XpressoException e) {
				comments = "There was a problem sending this email: " + 
					e.getDescription() + ". Message: " + e.getMessage();
			} finally {
				modifyFlagSent(email, comments);
				log.info("An email with subject:" + email.getSubject() + 
						" to: " + email.getTo()[0] + " has been processed by the queue. Result:" + comments);
			}
			
		}		
	}

	protected void modifyFlagSent(EmailMessage email, String comments) throws XpressoException {
		Query q = new Query();
		q.setQuery(UPDATE_EMAIL_QUEUE);
		q.setValues(new String[]{comments, email.getEmailId()});
		try {
			config.getApplicationDataSource().executeQuery(q);
		} catch (DataSourceException e) {
			throw new XpressoException("There was a problem modifying the email queue.", e);
		}
		
	}

	protected EmailMessage getEmailFromGrs(GenericResultSet grs) {
		EmailMessage email = new EmailMessage();
		email.setFrom(grs.getValue("FromEmail"));
		email.setFromName(grs.getValue("FromName"));
		email.setSubject(grs.getValue("Subject"));
		email.setBody(grs.getValue("Body"));
		email.setTo(grs.getValue("ToEmail").split(";"));
		email.setEmailId(grs.getValue("IdEmailQueue"));
		return email;
	}



}
